package com.simple.recvice;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

/**
 * Copyright (C) 2021
 * 版权所有
 * <p>
 * 功能描述：
 * <p>
 * 作者：tgl
 * 创建时间：2021/6/3
 * <p>
 * 修改人：
 * 修改描述：
 * 修改日期
 */
public class PhoneStateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (!TextUtils.equals(intent.getAction(), TelephonyManager.ACTION_PHONE_STATE_CHANGED)
                || !intent.hasExtra(TelephonyManager.EXTRA_INCOMING_NUMBER)) {
            return;
        }
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        String phoneNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        int state = telephonyManager.getCallState();
        switch (state) {
            case TelephonyManager.CALL_STATE_RINGING:
                Log.e("tgl===", "电话来了：" + phoneNumber);
                break;
            case TelephonyManager.CALL_STATE_IDLE:
                Log.e("tgl===", "电话挂断：" + phoneNumber);
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:
                Log.e("tgl===", "拨号即为通话中：" + phoneNumber);
                break;
        }
    }

    public static void requestPermissions(Activity activity) {
        //需要请求这些权限，才能获取来电或播出到手机号码
        activity.requestPermissions(new String[]{
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.READ_CALL_LOG,
        }, 1);

//        manifest注册广播
//        <receiver android:name=".PhoneStateReceiver">
//            <intent-filter>
//                <action android:name="android.intent.action.PHONE_STATE"/>
//                <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
//            </intent-filter>
//        </receiver>
    }
}